package com.yuanzong.wuliu.common.utils.tree;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.yuanzong.wuliu.common.utils.tree.reflect.method.ReflectCallMethod;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Data
public final class ObjectTree<E> {

    // 当前节点ID
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    private Object id;

    // 当前节点名称
    private Object name;

    // 父节点ID
    private Object parentId;

    // 节点数据
    private E entry;

    // 选中状态
    private Integer selected = 0;

    // 子节点列表
    private List<ObjectTree<E>> children = new ArrayList<>();

    public boolean equalsParent(Object topSign) {
        if (this.parentId == null) {
            return false;
        }
        if (this.parentId.equals(topSign)) {
            return true;
        }
        return false;
    }

    public static ObjectTree build(Object entry, String idName, String parentIdName) {
        ObjectTree objectTree = new ObjectTree();
        objectTree.setId(ReflectCallMethod.getInvokeByFieldName(entry, idName));
        objectTree.setParentId(ReflectCallMethod.getInvokeByFieldName(entry, parentIdName));
        objectTree.setEntry(entry);
        return objectTree;
    }

    public static <I> ObjectTree build(Object entry, Set<I> selectedIds) {
        ObjectTree objectTree = build(entry, "id", "parentId");
        // 给个名称
        Object name = ReflectCallMethod.getInvokeByFieldName(entry, "name");
        objectTree.setName(name);
        // 是否选中
        if (selectedIds != null && selectedIds.size() > 0) {
            if (selectedIds.contains(objectTree.getId())) {
                objectTree.setSelected(1);
            }
        }
        return objectTree;
    }

}
